package com.dnjn.happiness.survey.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.common.core.constant.Constants;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.job.api.RemoteJobService;
import com.dnjn.happiness.survey.domain.Question;
import com.dnjn.happiness.survey.domain.Survey;
import com.dnjn.happiness.survey.domain.SurveyIntervalScore;
import com.dnjn.happiness.survey.domain.SurveyRecord;
import com.dnjn.happiness.survey.domain.SurveyTemplate;
import com.dnjn.happiness.survey.domain.Tiku;
import com.dnjn.happiness.survey.domain.TikuTags;
import com.dnjn.happiness.survey.mapper.SurveyRecordMapper;
import com.dnjn.happiness.survey.mapper.SurveyTemplateMapper;
import com.dnjn.happiness.survey.service.IQuestionService;
import com.dnjn.happiness.survey.service.ISurveyIntervalScoreService;
import com.dnjn.happiness.survey.service.ISurveyService;
import com.dnjn.happiness.survey.service.ISurveyTemplateService;
import com.dnjn.happiness.survey.service.ITikuService;
import com.dnjn.happiness.survey.service.ITikuTagsService;
import com.dnjn.happiness.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 问卷 服务实现类
 * </p>
 *
 * @author Amber
 * @since 2023-10-04
 */
@Service
public class SurveyTemplateServiceImpl extends ServiceImpl<SurveyTemplateMapper, SurveyTemplate> implements ISurveyTemplateService {
    public static final String SURVEYSTATUSNO = "N";//未参加
    public static final String SURVEYSTATUSYES = "Y";//已参加
    public static final String TYPECOMMON = "COMMON";//普通问卷
    public static final String TYPECOMMUNICATE = "COMMUNICATE";//沟通问卷

    public static final String BUILTIN_SURVEY = "BUILTIN";//内置问卷
    public static final String CUSTOM_SURVEY = "CUSTOM";//自定义问卷
    public static final String QUESTION_TYPE_COMMON = "COMMON";//普通

    @Autowired
    private SurveyTemplateMapper surveyTemplateMapper;

    @Autowired
    private ITikuService tikuService;

    @Autowired
    private ISurveyIntervalScoreService intervalScoreService;

    @Autowired
    private ITikuTagsService tikuTagsService;

    @Autowired
    private ISurveyService surveyService;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveBuiltInSurvey(SurveyTemplate domain) {
        //拿到当前登录用户作用发起人
        domain.setSurveyType(BUILTIN_SURVEY);
        //获取当前登录用户作为发起者
        SysUser user = SecurityUtils.getLoginUser().getUser();
        domain.setInitiatorId(user.getUserId());
        domain.setSurveyStatus("READY");
        if (CollectionUtils.isEmpty(domain.getTimuIds())) {
            List<Tiku> list = tikuService.lambdaQuery().eq(Tiku::getTikuTagsId, domain.getTikuTagsId()).list();
            if (!CollectionUtils.isEmpty(list)) {
                domain.setTimuIds(list.stream().map(Tiku::getTikuId).collect(Collectors.toList()));
            }
        }
        domain.setTikuIds(domain.getTimuIds().stream().map(String::valueOf).collect(Collectors.joining(",")));
        //先保存问卷
        int count = surveyTemplateMapper.insert(domain);
        //保存问卷分值区间信息
        List<SurveyIntervalScore> intervalScoreList = domain.getIntervalScoreList();
        if (null != intervalScoreList && intervalScoreList.size() > 0) {
            for (SurveyIntervalScore surveyIntervalScore : intervalScoreList) {
                if (!ObjectUtils.isEmpty(surveyIntervalScore.getStartScore()) && !ObjectUtils.isEmpty(surveyIntervalScore.getEndScore())) {
                    surveyIntervalScore.setSurveyId(domain.getSurveyId());
                    intervalScoreService.save(surveyIntervalScore);
                }
            }
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addCustomSurvey(SurveyTemplate domain) {
        //拿到当前登录用户作用发起人
        domain.setSurveyType(CUSTOM_SURVEY);
        domain.setQuestionType(QUESTION_TYPE_COMMON);
        //获取当前登录用户作为发起者
        SysUser user = SecurityUtils.getLoginUser().getUser();
        domain.setInitiatorId(user.getUserId());
        domain.setSurveyStatus("READY");
        List<Tiku> tikuList = domain.getTikuList();
        if (CollectionUtils.isEmpty(tikuList)) {
            return AjaxResult.error("自定义题目列表为空");
        }
        StringBuilder tikuIds = new StringBuilder();
        Long tikuTagsId = domain.getTikuTagsId();
        for (Tiku tiku : tikuList) {
            tiku.setTikuTagsId(tikuTagsId);
            tikuService.save(tiku);
            tikuIds.append(tiku.getTikuId()).append(",");
        }
        domain.setTikuIds(tikuIds.substring(0, tikuIds.length() - 1));
        //先保存问卷
        int count = surveyTemplateMapper.insert(domain);
        return AjaxResult.success(count);
    }



    private void setMinAndMaxScore(SurveyTemplate domain, List<Long> timuIds) {
        Integer minScore = 0;
        Integer maxScore = 0;
        for (Long tikuId : timuIds) {
            Tiku tiku = tikuService.getById(tikuId);
            if ("select".equals(tiku.getIsSelectPack())) {
                Integer minCount = 0;
                Integer maxCount = 0;
                //多选-最小值-选项中最小的一个值， 最大值 全部选项值加起来
                Integer scoreOptionA = tiku.getScoreOptionA();
                Integer scoreOptionB = tiku.getScoreOptionB();
                Integer scoreOptionC = tiku.getScoreOptionC();
                Integer scoreOptionD = tiku.getScoreOptionD();
                Integer scoreOptionE = tiku.getScoreOptionE();
                Integer scoreOptionF = tiku.getScoreOptionF();
                Integer scoreOptionG = tiku.getScoreOptionG();

                List<Integer> list = new ArrayList<>();
                if (!ObjectUtils.isEmpty(scoreOptionA)) {
                    list.add(scoreOptionA);
                }
                if (!ObjectUtils.isEmpty(scoreOptionB)) {
                    list.add(scoreOptionB);
                }
                if (!ObjectUtils.isEmpty(scoreOptionC)) {
                    list.add(scoreOptionC);
                }
                if (!ObjectUtils.isEmpty(scoreOptionD)) {
                    list.add(scoreOptionD);
                }
                if (!ObjectUtils.isEmpty(scoreOptionE)) {
                    list.add(scoreOptionE);
                }
                if (!ObjectUtils.isEmpty(scoreOptionF)) {
                    list.add(scoreOptionF);
                }
                if (!ObjectUtils.isEmpty(scoreOptionG)) {
                    list.add(scoreOptionG);
                }
                if ("Y".equals(tiku.getIsMultipleChoice())) {
                    minCount = Collections.min(list);
                    minScore += minCount;
                    maxCount = list.stream().mapToInt(item -> item).sum();
                    maxScore += maxCount;
                }
                //单选-计算每个选项的 最小值，最大值
                if ("N".equals(tiku.getIsMultipleChoice())) {
                    minCount = Collections.min(list);
                    minScore += minCount;
                    maxCount = Collections.max(list);
                    maxScore += maxCount;
                }
            }
        }
        domain.setMinScore(minScore);
        domain.setMaxScore(maxScore);
    }

    @Override
    public Page<SurveyTemplate> selectPageSurvey(SurveyTemplate domain, Page page) {
        Page<SurveyTemplate> templatePage = surveyTemplateMapper.selectPageSurvey(domain, page);
        if (!CollectionUtils.isEmpty(templatePage.getRecords())) {
            for (SurveyTemplate template : templatePage.getRecords()) {
                System.out.println(template);
                Long count = surveyService.lambdaQuery().eq(Survey::getSurveyTemplateId, template.getSurveyId()).eq(Survey::getDeleted, Constants.UNDELETED).count();
                template.setCount(count.intValue());
            }
        }
        return templatePage;
    }

    @Override
    public void endSurveyId(Long surveyId) {
        surveyTemplateMapper.endSurveyId(surveyId);
    }

    @Override
    public void issuedSurveyId(Long surveyId) {
        surveyTemplateMapper.issuedSurveyId(surveyId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSurvey(SurveyTemplate domain) {
        //拿到当前登录用户作用发起人
//        SysUser user = SecurityUtils.getLoginUser().getUser();//获取当前登录用户作为发起者
        //先保存问卷
        int i = surveyTemplateMapper.updateById(domain);
        Long surveyId = domain.getSurveyId();
        if (CollectionUtils.isEmpty(domain.getTimuIds())) {
            List<Tiku> list = tikuService.lambdaQuery().eq(Tiku::getTikuTagsId, domain.getTikuTagsId()).list();
            if (!CollectionUtils.isEmpty(list)) {
                domain.setTimuIds(list.stream().map(Tiku::getTikuId).collect(Collectors.toList()));
            }
        }
        domain.setTikuIds(domain.getTimuIds().stream().map(String::valueOf).collect(Collectors.joining(",")));
        //保存问卷分值区间信息
        intervalScoreService.deleteBySurveyId(surveyId);
        List<SurveyIntervalScore> intervalScoreList = domain.getIntervalScoreList();
        if (null != intervalScoreList && intervalScoreList.size() > 0) {
            for (SurveyIntervalScore surveyIntervalScore : intervalScoreList) {
                if (!ObjectUtils.isEmpty(surveyIntervalScore.getStartScore()) && !ObjectUtils.isEmpty(surveyIntervalScore.getEndScore())) {
                    surveyIntervalScore.setSurveyId(domain.getSurveyId());
                    intervalScoreService.save(surveyIntervalScore);
                }
            }
        }
        return i;
    }

    @Override
    public Boolean deleteSurvey(Long surveyId) {
        return lambdaUpdate().set(SurveyTemplate::getDeleted, "1").eq(SurveyTemplate::getSurveyId, surveyId).update();
    }

    @Override
    public int editCustomSurvey(SurveyTemplate domain) {
        //先删除之前自定义的tiku
        SurveyTemplate oldTemplate = baseMapper.selectById(domain.getSurveyId());
        if (StringUtils.isNotEmpty(oldTemplate.getTikuIds())) {
            for (String tikuId : oldTemplate.getTikuIds().split(",")) {
                tikuService.removeById(tikuId);
            }
        }
        StringBuilder tikuIds = new StringBuilder();
        Long tikuTagsId = domain.getTikuTagsId();
        List<Tiku> tikuList = domain.getTikuList();
        if (!CollectionUtils.isEmpty(tikuList)) {
            for (Tiku tiku : tikuList) {
                tiku.setTikuTagsId(tikuTagsId);
                tikuService.saveOrUpdate(tiku);
                tikuIds.append(tiku.getTikuId()).append(",");
            }
        }
        //先删除之前题库题目，再新增题库题目
        domain.setTikuIds(tikuIds.substring(0, tikuIds.length() - 1));
        int i = surveyTemplateMapper.updateById(domain);
        return i;
    }


    @Override
    public SurveyTemplate getSurveyTemplateById(Long surveyId) {
        SurveyTemplate survey = baseMapper.selectById(surveyId);
        if (!ObjectUtils.isEmpty(survey.getTikuTagsId())) {
            TikuTags tikuTags = tikuTagsService.lambdaQuery().eq(TikuTags::getTikuTagsId, survey.getTikuTagsId()).one();
            survey.setLabel(tikuTags.getLabel());
            String tikuIds = survey.getTikuIds();
            List<Long> tikuIdList = new ArrayList<>();
            if (StringUtils.isNotEmpty(tikuIds)) {
                for (String tikuId : tikuIds.split(",")) {
                    if (!Objects.isNull(tikuService.getById(tikuId))) {
                        tikuIdList.add(tikuService.getById(tikuId).getTikuId());
                    }
                }
            }
            survey.setTimuIds(tikuIdList);
        }
        List<SurveyIntervalScore> intervalScoreList = intervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyId).list();
        survey.setIntervalScoreList(intervalScoreList);
        return survey;
    }


    @Override
    public SurveyTemplate getTemplateById(Long surveyId) {
        SurveyTemplate survey = baseMapper.selectById(surveyId);
        if (!ObjectUtils.isEmpty(survey.getTikuTagsId())) {
            TikuTags tikuTags = tikuTagsService.lambdaQuery().eq(TikuTags::getTikuTagsId, survey.getTikuTagsId()).one();
            survey.setLabel(tikuTags.getLabel());
        }
        //返回所属tikuList
        String tikuIds = survey.getTikuIds();
        List<Tiku> tikuIdList = new ArrayList<>();
        if (StringUtils.isNotEmpty(tikuIds)) {
            for (String tikuId : tikuIds.split(",")) {
                if (!Objects.isNull(tikuService.getById(tikuId))) {
                    tikuIdList.add(tikuService.getById(tikuId));
                }
            }
        }
        survey.setTikuList(tikuIdList);
        List<SurveyIntervalScore> intervalScoreList = intervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyId).list();
        survey.setIntervalScoreList(intervalScoreList);
        return survey;
    }


}
